package com.example.springcloudjwtserver.util;

import com.example.springcloudjwtserver.user.domain.AdminUser;
import io.jsonwebtoken.*;
import java.util.Date;

public class JwtUtil {

    private static final String JWT_KEY = "9876512";


    /**
     * 生成jwt信息
     * @param adminUser
     * @return
     */
    public static String generateJwt(AdminUser adminUser) {

//        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
//        SecretKey key = Keys.hmacShaKeyFor(JWT_KEY.getBytes());


        JwtBuilder builder = Jwts.builder()
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60))
                .signWith(SignatureAlgorithm.HS256,JWT_KEY)
                .setId(String.valueOf(adminUser.getUserId()))
                .setSubject("user")
                .claim("name", adminUser.getName())
                .claim("tel", adminUser.getTel());
        return builder.compact();

    }


    /**
     * 生成jwt信息
     * @param jwt
     * @return
     */
    public static boolean verifyJwt(String jwt) {
//        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
//        SecretKey key = Keys.hmacShaKeyFor(JWT_KEY.getBytes());

        try {
//            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt);
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(JWT_KEY).parseClaimsJws(jwt);
            System.out.println(claimsJws);
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


    }

    public static void main(String[] args) {

        AdminUser adminUser = new AdminUser();
        adminUser.setUserId(1);
        adminUser.setName("sss");
        adminUser.setTel("11142131");


        String jwt = generateJwt(adminUser);

        System.out.println(jwt);
        verifyJwt(jwt);
    }


}
